<template>
  <div class="page-container">
    <div class="page-header">
      <h2>论文文档管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="学生姓名">
        <el-input v-model="searchForm.student_name" placeholder="请输入学生姓名" clearable />
      </el-form-item>
      <el-form-item label="题目">
        <el-input v-model="searchForm.topic_title" placeholder="请输入题目" clearable />
      </el-form-item>
      <el-form-item label="文档类型">
        <el-select v-model="searchForm.type" placeholder="请选择文档类型" clearable>
          <el-option label="开题报告" value="proposal" />
          <el-option label="中期报告" value="midterm" />
          <el-option label="论文初稿" value="draft" />
          <el-option label="论文终稿" value="final" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 文档列表 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="documents"
        style="width: 100%"
      >
        <el-table-column prop="student_name" label="学生姓名" />
        <el-table-column prop="topic_title" label="题目" show-overflow-tooltip />
        <el-table-column prop="teacher_name" label="指导教师" />
        <el-table-column prop="type" label="文档类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getDocumentType(row.type)">
              {{ getDocumentTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitted_at" label="提交时间" width="180" />
        <el-table-column prop="feedback" label="反馈意见" show-overflow-tooltip />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="isStudent && row.status === 'draft'"
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="isTeacher && row.status === 'submitted'"
              type="success"
              link
              @click="handleApprove(row)"
            >
              通过
            </el-button>
            <el-button
              v-if="isTeacher && row.status === 'submitted'"
              type="danger"
              link
              @click="handleReject(row)"
            >
              驳回
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="row.file_url"
              type="success"
              link
              @click="handleDownload(row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑文档' : '提交文档'"
      width="600px"
    >
      <el-form
        ref="documentFormRef"
        :model="documentForm"
        :rules="documentRules"
        label-width="100px"
      >
        <el-form-item label="文档类型" prop="type">
          <el-select v-model="documentForm.type" placeholder="请选择文档类型">
            <el-option label="开题报告" value="proposal" />
            <el-option label="中期报告" value="midterm" />
            <el-option label="论文初稿" value="draft" />
            <el-option label="论文终稿" value="final" />
          </el-select>
        </el-form-item>
        <el-form-item label="文档文件" prop="file">
          <el-upload
            class="upload-demo"
            action="/api/thesis/documents/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传 PDF 或 Word 文档，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="文档说明" prop="description">
          <el-input
            v-model="documentForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入文档说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="文档详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="学生姓名">
          {{ currentDocument.student_name }}
        </el-descriptions-item>
        <el-descriptions-item label="题目">
          {{ currentDocument.topic_title }}
        </el-descriptions-item>
        <el-descriptions-item label="指导教师">
          {{ currentDocument.teacher_name }}
        </el-descriptions-item>
        <el-descriptions-item label="文档类型">
          <el-tag :type="getDocumentType(currentDocument.type)">
            {{ getDocumentTypeText(currentDocument.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDocument.status)">
            {{ getStatusText(currentDocument.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">
          {{ currentDocument.submitted_at }}
        </el-descriptions-item>
        <el-descriptions-item label="文档说明">
          {{ currentDocument.description }}
        </el-descriptions-item>
        <el-descriptions-item label="反馈意见">
          {{ currentDocument.feedback }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 驳回对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="驳回文档"
      width="500px"
    >
      <el-form
        ref="rejectFormRef"
        :model="rejectForm"
        :rules="rejectRules"
        label-width="100px"
      >
        <el-form-item label="驳回原因" prop="feedback">
          <el-input
            v-model="rejectForm.feedback"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRejectSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useUserStore } from '../../store'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const isStudent = computed(() => userStore.isStudent)
const isTeacher = computed(() => userStore.isTeacher)

// 搜索表单
const searchForm = ref({
  student_name: '',
  topic_title: '',
  type: ''
})

// 表格数据
const loading = ref(false)
const documents = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 编辑表单
const editDialogVisible = ref(false)
const isEdit = ref(false)
const documentFormRef = ref(null)
const documentForm = ref({
  id: null,
  type: '',
  file: null,
  description: ''
})
const documentRules = {
  type: [
    { required: true, message: '请选择文档类型', trigger: 'change' }
  ],
  file: [
    { required: true, message: '请上传文档文件', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入文档说明', trigger: 'blur' }
  ]
}

// 查看对话框
const viewDialogVisible = ref(false)
const currentDocument = ref({})

// 驳回表单
const rejectDialogVisible = ref(false)
const rejectFormRef = ref(null)
const rejectForm = ref({
  id: null,
  feedback: ''
})
const rejectRules = {
  feedback: [
    { required: true, message: '请输入驳回原因', trigger: 'blur' }
  ]
}

// 获取文档类型
const getDocumentType = (type) => {
  const map = {
    proposal: 'primary',
    midterm: 'success',
    draft: 'warning',
    final: 'info'
  }
  return map[type] || 'info'
}

// 获取文档类型文本
const getDocumentTypeText = (type) => {
  const map = {
    proposal: '开题报告',
    midterm: '中期报告',
    draft: '论文初稿',
    final: '论文终稿'
  }
  return map[type] || type
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    draft: 'info',
    submitted: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    draft: '草稿',
    submitted: '已提交',
    approved: '已通过',
    rejected: '已驳回'
  }
  return map[status] || status
}

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    const response = await fetch(`/api/thesis/documents?page=${currentPage.value}&page_size=${pageSize.value}&${new URLSearchParams(searchForm.value)}`)
    const data = await response.json()
    documents.value = data.items
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchDocuments()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    student_name: '',
    topic_title: '',
    type: ''
  }
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDocuments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDocuments()
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  documentForm.value = {
    id: row.id,
    type: row.type,
    file: null,
    description: row.description
  }
  editDialogVisible.value = true
}

// 上传相关
const handleUploadSuccess = (response) => {
  documentForm.value.file = response.data
  ElMessage.success('上传成功')
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 提交
const handleSubmit = async () => {
  if (!documentFormRef.value) return
  
  await documentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await fetch(`/api/thesis/documents${isEdit.value ? `/${documentForm.value.id}` : ''}`, {
          method: isEdit.value ? 'PUT' : 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(documentForm.value)
        })
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? '更新成功' : '提交成功')
          editDialogVisible.value = false
          fetchDocuments()
        } else {
          throw new Error(isEdit.value ? '更新失败' : '提交失败')
        }
      } catch (error) {
        ElMessage.error(error.message)
      }
    }
  })
}

// 查看
const handleView = (row) => {
  currentDocument.value = row
  viewDialogVisible.value = true
}

// 下载
const handleDownload = (row) => {
  window.open(row.file_url)
}

// 通过
const handleApprove = async (row) => {
  try {
    const response = await fetch(`/api/thesis/documents/${row.id}/approve`, {
      method: 'POST'
    })
    
    if (response.ok) {
      ElMessage.success('操作成功')
      fetchDocuments()
    } else {
      throw new Error('操作失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 驳回
const handleReject = (row) => {
  rejectForm.value = {
    id: row.id,
    feedback: ''
  }
  rejectDialogVisible.value = true
}

// 提交驳回
const handleRejectSubmit = async () => {
  if (!rejectFormRef.value) return
  
  await rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await fetch(`/api/thesis/documents/${rejectForm.value.id}/reject`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(rejectForm.value)
        })
        
        if (response.ok) {
          ElMessage.success('操作成功')
          rejectDialogVisible.value = false
          fetchDocuments()
        } else {
          throw new Error('操作失败')
        }
      } catch (error) {
        ElMessage.error(error.message)
      }
    }
  })
}

// 初始化
fetchDocuments()
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 